/**
 * $Id: SGIPDeliverConnector.java,v 1.49 2006/09/07 02:07:43 martin Exp $
 *
 * Copyright 2006 Skyinfo, Inc. All Rights Reserved.
 */
package com.haoxi.gateway.connector.impl;

import java.io.EOFException;
import java.io.IOException;
import java.net.SocketException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.haoxi.gateway.common.CommonMsgBean;
import com.haoxi.gateway.connector.Connector;
import com.haoxi.gateway.runner.RunnerMgr;
import com.haoxi.gateway.sgip12msg.SGIPActiveMessage;
import com.haoxi.gateway.sgip12msg.SGIPActiveRepMessage;
import com.haoxi.gateway.sgip12msg.SGIPBindMessage;
import com.haoxi.gateway.sgip12msg.SGIPBindRepMessage;
import com.haoxi.gateway.sgip12msg.SGIPCommon;
import com.haoxi.gateway.sgip12msg.SGIPDeliverMessage;
import com.haoxi.gateway.sgip12msg.SGIPDeliverRepMessage;
import com.haoxi.gateway.sgip12msg.SGIPMessage;
import com.haoxi.gateway.sgip12msg.SGIPReportMessage;
import com.haoxi.gateway.sgip12msg.SGIPReportRepMessage;
import com.haoxi.gateway.sgip12msg.SGIPUnbindMessage;
import com.haoxi.gateway.sgip12msg.SGIPUnbindRepMessage;

/**
 * 联通deliver下发连接
 * 
 * Revision History
 * 
 * 2006-6-14,star.Zhao,created it
 */
public class SGIPDeliverConnector extends Connector {
    private static final Log log = LogFactory
            .getLog(SGIPDeliverConnector.class);

    // private long lastReciveOrSendTime = System.currentTimeMillis();
    public SGIPDeliverConnector(String aGatewayName, String connName,
            String aICP_ID, String loginName, String aPassword,
            String aGatewayIP, int aGatewayPort, int sVersion,
            String protcolName) {
        super(aGatewayName, connName, aICP_ID, loginName, aPassword,
                aGatewayIP, aGatewayPort, sVersion, protcolName);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.haoxi.gateway.connector.Connector#openConnect()
     */
    public boolean openConnect() {
        boolean bOK = false;
        log.debug("--------Start startup the SGIPDeliverServer--------");
        try {
            // 启动服务
            SgipAdapter adapter = new SgipAdapter(this.gatewayPort,
                    this.maxConnCount, this);
            adapter.startService();
            bOK = true;
        } catch (Exception e) {
            log
                    .debug(
                            "--------Startup the SGIPDeliverServer unsuccessfully!--------",
                            e);
            bOK = false;
        }
        log
                .debug("--------Startup the SGIPDeliverServer successfully!--------");
        return bOK;
    }

    public byte checkBind(SGIPBindMessage bindMessage) throws IOException {
        byte result = 1;
        // log.info(bindMessage.toString());
        String smgLoginName = bindMessage.getLoginName();
        String smgLoginPass = bindMessage.getLoginPass();
        int smgLoginType = bindMessage.getLoginType();
        if (smgLoginName.equals(loginName) && smgLoginPass.equals(password)
                && smgLoginType == 2) {
            isConnected = true;
            result = 0;
        }
        // 登陆名或密码错
        else if (!smgLoginName.equals(loginName)
                || !smgLoginPass.equals(password)) {
            result = 1;
        }
        // 登陆类型错
        else if (smgLoginType != 2) {
            result = 4;
        }
        return result;
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.haoxi.gateway.connector.Connector#readProtcol()
     */
    public CommonMsgBean readProtcol() throws IOException {
        CommonMsgBean result = null;
        byte[] bodybytes = new byte[0];
        int commid = 0;
        int readLength = 0;
        SGIPMessage respMessage = null;
        SGIPMessage reqMessage = null;
        byte bindresult = 0;
        if (soc != null && isSocketKeepLive && soc.isBound()
                && soc.isConnected() && (!soc.isInputShutdown())
                && (!soc.isOutputShutdown())) {
            try {
                int ch1 = in.read();
                if (ch1 < 0) {
                    return result;
                }
                int ch2 = in.read();
                int ch3 = in.read();
                int ch4 = in.read();
                readLength = ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
                commid = in.readInt();
                // 读取剩余部分
                bodybytes = new byte[readLength - 8];
                in.readFully(bodybytes);
            } catch (EOFException eof) {
                log.info("read the end of the stream has been reached!");
                return null;
            } catch (SocketException socex) {
                log.info(this.getConnName() + " socket is close!!!");
                this.disConnected();
                return null;
            }
        }
        // lastReciveOrSendTime = System.currentTimeMillis();
        // 登陆请求
        if (SGIPCommon.SGIP_BIND == commid) {
            log.info("<<<<<<deal SMG BindSGIPMessage>>>>>>");
            reqMessage = new SGIPBindMessage(bodybytes);
            bindresult = checkBind((SGIPBindMessage) reqMessage);
            if (0 == bindresult) {
                log
                        .info("UnicomSgipDeliver gateway bind sucessfully!bind result:["
                                + bindresult + "]");
            } else {
                log.error("UnicomSgipDeliver bind unsucessfully!bind result:["
                        + bindresult + "]");
            }
            respMessage = new SGIPBindRepMessage(bindresult);
        }
        // 接收到客户端SMG下发的deliver消息
        else if (SGIPCommon.SGIP_DELIVER == commid) {
            log.info("<<<<<<deal SMG DeliverSGIPMessage>>>>>>");
            reqMessage = new SGIPDeliverMessage(bodybytes);
            respMessage = new SGIPDeliverRepMessage(0);
        }
        // 接收到客户端SMG下发的report消息
        else if (SGIPCommon.SGIP_REPORT == commid) {
            log.info("<<<<<<deal SMG ReportSGIPMessage>>>>>>");
            reqMessage = new SGIPReportMessage(bodybytes);
            respMessage = new SGIPReportRepMessage(0);
        }
        // 接收到客户端SMG下发的unbind消息
        else if (SGIPCommon.SGIP_UNBIND == commid) {
            log.info("<<<<<<deal SMG UnBindSGIPMessage>>>>>>");
            reqMessage = new SGIPUnbindMessage(bodybytes);
            respMessage = new SGIPUnbindRepMessage();
        } else if (SGIPCommon.SGIP_ACTIVE_TEST == commid) {
            log.info("<<<<<<deal SMG ActiveSGIPMessage>>>>>>");
            reqMessage = new SGIPActiveMessage(bodybytes);
            respMessage = new SGIPActiveRepMessage();
        } else if (SGIPCommon.SGIP_UNBIND_RESP == commid) {
            log.info("<<<<<<deal SMG UnbindSGIPRepMessage>>>>>>");
            reqMessage = new SGIPUnbindRepMessage(bodybytes);
        } else if (SGIPCommon.SGIP_ACTIVE_TEST_RESP == commid) {
            log.info("<<<<<<deal SMG ActiveSGIPRepMessage>>>>>>");
            reqMessage = new SGIPActiveRepMessage(bodybytes);
        } else {
            log.info("<<<<<deal unkown message,message_length:[" + readLength
                    + "],commid:[" + commid + "],please check readProtcol()");
        }
        log.info(reqMessage.toString());
        if (null != respMessage) {
            respMessage.setSequenceId(reqMessage.getSequenceId());
            respMessage.setSrcNodeId(reqMessage.getSrcNodeId());
            respMessage.setTimeStamp(reqMessage.getTimeStamp());
            String gatewayCode = RunnerMgr.getInstance().getGatewayInfo()
                    .getGatewayCode();
            result = new CommonMsgBean();
            result.setGateWayCode(gatewayCode);
            result.setConnName(connName);
            result.setBody(bodybytes);
            result.setCommid(commid);
            result.setNeedSendResp(false);
            if (writeToOut(respMessage.getBytes())) {
                // disConnected();
                log.info("send response message successfull!");
            } else {
                log.error("send response message unsuccessfull!");
            }
            log.info(respMessage.toString());
        }
        // 收到unbind消息或服务端绑定不成功，关闭当前连接
        if (SGIPCommon.SGIP_UNBIND == commid || 0 != bindresult) {
            disConnected();
        }
        return result;
    }

    /*
     * (non-Javadoc) 根本没有用到此方法，放到这里是垃圾代码
     * 
     * @see com.haoxi.gateway.connector.Connector#writeProtcol(com.haoxi.gateway.common.CommonMsgBean)
     */
    public boolean writeProtcol(CommonMsgBean obj) throws IOException {
        // log.debug(this.connName + "start send msg！----------");
        // boolean result = false;
        // public boolean writeToOut(byte[] b) throws IOException
        // if (null != obj && null != obj.getBody()) {
        // lastReciveOrSendTime = System.currentTimeMillis();
        // if (!this.writeToOut(obj.getBody())) {
        // log.error(this.connName + " send msg unsuccessfully!");
        // result = false;
        // } else {
        // result = true;
        // }
        //
        // } else {
        // result = false;
        // log.error(this.connName + " send null unsuccessfully!");
        // }
        return false;
    }

    /*
     * 由于是运营商是客户端，所以不需要checkConnect
     * 
     * @see com.haoxi.gateway.connector.Connector#checkConnect(java.lang.String,
     *      java.lang.String)
     */
    public boolean checkConnect(String loginName, String password) {
        return false;
    }

}
